<template>
  <!--
  flex: 1：也就是 flex-grow: 1， 经常用于自适应布局；也就是设置父盒子为伸缩布局（display:flex），给子盒子设置flex: 1；这样做，内容区就会自动放大占满空间
  flex: 0 0 auto： 等同于 flex: none，默认元素有剩余空间也不放大，空间不足时也不能缩小，长度等于灵活项目的长度
  flex: 0 1 auto：默认有剩余空间也不放大，空间不足时可以缩小，长度等于灵活项目的长度
  flex: 1 0 auto：默认有剩余空间可以放大，空间不足时不缩小，长度等于灵活项目的长度
  flex: 1 1 auto：等同于 flex: auto ， 默认根据 width 和 height 属性调整元素的大小，
  flex: 0 0 10%：默认元素有剩余空间也不放大，空间不足时也不能缩小，长度占据当前项目总空间的10%
  -->
<!--  {{ template.list }}-->
  <form class="form-main">
    <!--表单内容区域 -->
    <div class="container" :key="rowItem" v-for="(rowItem,rowIndex) in template.list">
      <div class="col"
           :style="computeCol(colItem)"
           v-show="computeColShow(colItem)"
           :key="colItem.key" v-for="(colItem,colIndex) in rowItem">
        <div class="labelItem">
          {{ colItem.randomId }}

          <span v-if="colItem.configure && !(colItem.configure.type==='table')" class="spanItem">{{ colItem.name }}
          </span>
          <div v-if="colItem.configure && colItem.configure.type==='default'" class="inputItem">
            <input v-model="colItem.itemValue" type="text"
                   :placeholder="colItem.placeholder?colItem.placeholder:'请输入'">
          </div>
          <div v-if="colItem.configure && (colItem.configure.type==='img'||colItem.configure.type==='imgs')"
               class="rowItem">
            <input @change="upload($event,colItem)" id="inputFileItem" type="file" multiple class="inputFileItem"/>
            <div class="itemImgBox">
              <!--图片显示区域-->
              <customImg @synElementImgData="synElementImgData" :colItem="colItem" :index="colIndex"
                         :customImgList="colItem.itemValue.substr(0,colItem.itemValue.length).split(',')"
                         :superDivWidth="divWidth" flex-direction="column"></customImg>
            </div>
          </div>
          <div v-if="colItem.configure && colItem.configure.type==='table'" class="tableItem">
            <!--表格顶部操作栏-->
            <div>
              <commentHeader
                  :colItem="colItem"
                  :name="colItem.name">
                <template v-slot:buttons>
                  <!--头部按钮 -->
                  <CustomCommButton
                      :buttonClick="systemButton"
                      @buttonTrigger="buttonTrigger($event,rowIndex,colIndex)"
                      location="top"
                      :scope="colItem"
                      :colItem="colItem"
                      button-key="operationType"
                      :buttons="colItem.configure.buttons"></CustomCommButton>
                </template>
              </commentHeader>
            </div>
            <!--            {{colItem}}-->
            <!--            {{ colItem.configure.formTableData }}-->
            <el-Table :data="colItem.configure.formTableData"
                      :v-loading="colItem.configure.loaded"
                      border style="width: 100%">
              <el-table-column :key="item.key" v-for="(item) in setListFilter(colItem.configure.display_columns)"
                               :label="item.title"
                               :fixed="item.fixed?item.fixed:false"
                               :align="item.align"
                               :prop="item.key">
              </el-table-column>
              <!--按钮区域-->
              <el-table-column label="操作"
                               align="center"
                               :v-if="true"
                               fixed="right"
              >
                <template #default="scope">
                  <CustomCommButton
                      :buttonClick="systemButton"
                      :colItem="colItem"
                      @buttonTrigger="buttonTrigger($event,rowIndex,colIndex)"
                      :scope="scope"
                      location="action"
                      button-key="operationType"
                      :buttons="colItem.configure.buttons"></CustomCommButton>
                </template>
              </el-table-column>
            </el-Table>
          </div>
        </div>

      </div>
    </div>
    <!--按钮区域-->
    <div class="form-button">
      <CustomCommButton
          :buttonClick="onButton"
          :scope="dialogScope"
          :col-item="dialogColItem"
          :buttons="template.buttons"></CustomCommButton>
    </div>
    <!--  弹出层  -->
    <el-dialog
        width="1000px"
        v-if="dialog"
        v-model="dialog">
      <commentForm
          ref="commentForm"
          :functionType="dialogFunctionType"
          @setFromDataByIndex="setFromDataByIndex"
          :scope="dialogScope"
          :col-item="dialogColItem"
          :customClose="formClose"
          :fromTableBoolean="fromTableBooleanTag"
          :fromTemplateId="dialogFromTemplateId"
      >
      </commentForm>
    </el-dialog>
  </form>
</template>

<script>
import {post} from '../request/api'
import {
  findById, mSelectById,
  upload, listFilter,
  setListElement, getListElementToObj, selectCustomCondition, getRandomString
} from "@/components/request/publicApi";


export default {
  setup() {
    return {};
  },
  name: "CommentForm",
  props: {
    functionType: {type: String},
    scope: {type: Object},
    /*关闭接口*/
    customClose: {
      type: Function,
      require: false,
      default: null,
    },
    /*表单模板id*/
    fromTemplateId: {
      type: String,
      required: true,
    },
    colItem: {
      type: Object
    },
    /*表单字段*/
    list: {
      type: Array,
      default: () => [] // 默认值是空数组
    },
    /*表单按钮集合*/
    buttons: {
      type: Array,
      default: () => [] // 默认值是空数组
    },
    //对应的数据库
    source: {
      type: String,
      default: ""
    },
    fromTableBoolean: {
      type: Boolean
    },
  },
  data() {
    return {
      dialogFunctionType: "",
      dialogScope: {},
      dialog: false,
      arrayKeys: [],
      formFields: [],
      formData: {},
      template: {},
      wrap: true, // 控制是否换行
      columns: [6, 6], // 每列占据的宽度
      dialogImageUrl: '',
      dialogVisible: false,
      divWidth: 0,
      /*表单数据*/
      fromData: {},
      dialogFromTemplateId: "",
      dialogColItem: [],
      fromTableBooleanTag: false,
      dataColItem: this.colItem,
      //操作元素下标
      operationRowIndex: 0,
      operationColIndex: 0,
    }
  },
  inject: ["fClearDialog"],
  emits: ['setFromDataByIndex'],
  // provide() {
  //   return {
  //     fResetForm: this.resetForm,
  //     parDisplay: this.parDisplay,
  //   };
  // },
  components: {},
  computed: {
    setLoading: () => {
      return (item) => {
        if (item.formTableData) {
          console.log(item.formTableData)
          return true
        } else {
          console.log(item)
          return false
        }
      }
    },
    /*表格的返回字段*/
    setListFilter: function () {
      return function (list) {
        // console.log('listFilter',list)
        return listFilter(list, true, "hidden");
      }
    },
    /**
     * 动态样式
     * @returns {function(*): {flex: string}}
     */
    computeCol: function () {
      return function (colItem) {
        // 计算值 flex: 0 0 calc((100% - 100px) / 24 * 8) 占8 栏 共24栏
        // return {'flex': '0 0 calc((100% - 20px) / 24 * ' + colItem.configure.span + ')'};
        return {'flex': colItem.configure.span};

      }
    },
    computeColShow: function () {
      return function (colItem) {
        return colItem['configure'] && colItem['configure'].display !== undefined ? colItem['configure'].display : true;
        // 判断 obj2.config.show 是否存在
        // if (colItem['configure'] && colItem['configure'].display !== undefined) {
        //   return colItem['configure'].display;
        // } else {
        //   return true;
        // }

      }
    },
    colWidth() {
      return Math.floor(24 / this.columns.length); // 计算每列的宽度，假设总宽度为24
    },
    /*设置span比例*/
    getSpan() {
      // console.log('this.config', this.template)
      let span = 24 / (this.template.config.showPercent);

      console.log('span', span)
      return parseInt(span);
    },
    calc() {
      return 'count-' + this.count
    }
  },
  methods: {
    setFromDataByIndex(parMap) {
      let array = this.template.list[this.operationRowIndex] [this.operationColIndex].configure.formTableData;
      console.log('array.length', array.length)
      for (let i = 0; i < array.length; i++) {
        let element = array[i];
        console.log('i', i)
        console.log('parMap', parMap)
        console.log('element', element)
        console.log('boolean', i, parMap.randomId, element.randomId,
            parMap.id, element.id,
            parMap.randomId === element.randomId || parMap.id === element.id)
        if (element.id !== undefined || parMap.id !== undefined) {
          if (parMap.id === element.id) {
            console.log('operationRowIndex', i, parMap)
            array[i] = parMap;
            break;
          }
        }
        if (element.randomId !== undefined || parMap.randomId !== undefined) {
          if (parMap.randomId === element.randomId) {
            console.log('operationRowIndex', i, parMap)
            array[i] = parMap;
            break;
          }
        }
      }
      console.log('operationColIndex', this.template.list[this.operationRowIndex] [this.operationColIndex].configure.formTableData)
      // this.customClose()
    },

    formClose() {
      this.dialog = false;
    },

    buttonTrigger(item, rowIndex, colIndex) {
      console.log('buttonTrigger', this.template.list, rowIndex, colIndex)
      this.operationRowIndex = rowIndex;
      this.operationColIndex = colIndex;
    },

    /*按钮触发事件*/
    systemButton(item, scope, colItem) {

      this.dialogScope = scope;
      this.dialogFromTemplateId = item.templateId;
      this.dialogFunctionType = item.functionType;
      this.dialogColItem = colItem.configure.formTableData;
      this.fromTableBooleanTag = true;
      console.log('按钮触发事件item', this.fromTableBooleanTag, item, scope)
      this.dialog = true;


    },

    /*表单中的表格数据init*/
    tableListDataInit(item) {
      if (item.customInterface === 'default') {
        let dataPar = {
          "andStr": [
            {
              "key": item.foreignField,
              "value": this.fromData[item.localField],
              "type": "eq"
            }
          ],
          page: 1,
          pageSize: 100,
        };
        //默认
        //获取表格的初始数据
        selectCustomCondition(item.tableSource, dataPar)
            .then((res) => {
              //设置数据
              console.log('selectCustomCondition', res)
              item.formTableData = res.data.data;
              item.loaded = true;
              // this.countSize = res.data.countSize;
              // this.checkBoxIds = [];
            }).catch((error) => {
          this.$message.error("操作失败")
        })
      } else {
        console.log('selectCustomCondition', res)

      }
    },
    /*同步*/
    synElementImgData(val, colItem, index) {
      // console.log('synElementImgData', val, colItem, index)
      colItem.itemValue = val;
      // this.
    },
    /*删除按钮*/
    itemImgDel(array, index) {
      console.log(typeof array)
      array.itemValue.slice(',').splice(index, 1)
    },
    hideDel() {
      // console.log('隐藏')
      document.getElementById("itemImgDelBox").style.display = "none";
    },
    showDel() {
      // console.log('显示')
      /*cursor: pointer*/
      document.getElementById("itemImgDelBox").style.display = "inline-block";
      /*document.getElementById("itemImgDelBox").style.cursor = "pointer";*/
    },
    /*图片上传的触发方法*/
    uploadImg() {
      // console.log('aaa')
      // document.getElementById("inputFileItem")
      //     .click()
      let inputFileItem = document.getElementById("inputFileItem");
      inputFileItem.click();
      // return;
    },
    /*文件上传*/
    upload(event, colItem) {
      // console.log('文件上传信息', event, colItem)
      let data = {'file': event.target.files[0]}
      upload(data).then((res) => {

        colItem.itemValue = res.data.data.path;
        // console.log('文件返回信息', res, colItem)
      })
          .catch(error => {
            console.log(error)
          })
    },
    submitForm() {
      // 提交表单逻辑，可以在这里处理表单验证等操作
      // console.log('表单数据：', this.formData);
    },
    getLabelWidth: function (item) {

      let labelWidth;
      console.log(item)
      if (item.labelWidth) {
        labelWidth = item.labelWidth;
      } else {
        labelWidth = this.config.labelWidth;
      }
      console.log(labelWidth)
      return labelWidth;
    },
    onButton(item, scope, colItem) {
      //获取操作类型
      let action = this.functionType;
      console.log('获取操作类型 onButton', item, scope, colItem, this.fromTableBooleanTag)

      if ('add' === action && item.functionType !== 'close') {
        if (this.fromTableBoolean) {
          let parMap = {};
          getListElementToObj(this.template.list, "id", "itemValue", parMap)
          parMap['dataDisposeState'] = 'add';
          //随机id
          parMap['randomId'] = getRandomString(10);
          parMap['id'] = getRandomString(10);
          this.colItem.push(parMap);
          this.customClose()
        } else {
          //参数处理
          let parMap = {};
          getListElementToObj(this.template.list, "id", "itemValue", parMap)

          // if (this.scope.row&&this.scope.row._id){
          //   parMap
          // }
          let serverUrl = "";
          serverUrl = "/comm/one/saveValue/" + this.template.source;
          console.log("add", parMap)
          post(serverUrl, parMap)
              .then(res => {
                console.log(res)
                if (res.data.code === 200) {
                  this.$message.success(res.data.message ? '操作成功' : res.data.message)
                  this.customClose()
                }
              })
              .catch(error => {
                console.log(error)
              })
        }

      } else if ('close' === action || item.functionType === 'close') {
        this.customClose()
      } else if ('reset' === action) {
        //重置
        this.resetForm();
        // console.log("重置")
      } else if ('update' === action && this.fromTableBoolean && item.functionType !== 'close') {
        let parMap = {};
        getListElementToObj(this.template.list, "id", "itemValue", parMap)
        // setListElement(this.colItem, "id", "itemValue", res.data.data);
        for (let colItemElement of this.colItem) {
          if (colItemElement.id === parMap.id) {
            colItemElement = parMap;
            break;
          }
        }
        let replaceList = [];
        for (let colItemElement of this.colItem) {
          if (parMap.randomId === colItemElement.randomId) {
            // console.log("update", parMap, this.colItem)
            parMap.dataDisposeState = 'update';
            // colItemElement = parMap;
            replaceList.push(parMap)
          } else {
            replaceList.push(colItemElement)
          }
        }
        this.dataColItem = replaceList;
        this.$emit('setFromDataByIndex', parMap)
        console.log('获取操作类型 onButton', this.functionType)
        this.customClose()
      } else {

      }


    },
    parDisplay() {
      let parList = this.template.list
      let parMap = {};
      for (const parListElement of parList) {
        parMap[parListElement.id] = parListElement.itemValue
      }
      return parMap;
    },
    /*重置表单*/
    resetForm() {
      this.template.list.forEach(em => {
        em.itemValue = ""
      })
    },
    /*清空表单*/
    emptyForm() {
      if (this.template.list) {
        this.template.list.forEach(em => {
          em.forEach(emA => {
            emA.itemValue = ""
          })
        })
      }
    }
  },
  mounted() {
    // 在组件挂载后获取 <div> 的宽度
    // this.divWidth = this.$refs.itemImgBox.clientWidth;
    let addFromPar = {
      "source": "A_TEMPLATE",
      "_id": this.fromTemplateId,
    };
    findById(addFromPar).then((res) => {
      this.template = res.data.data;
      console.log(' this.template', this.template)
      if ('add' === this.functionType) {
        //初始化表单
        this.emptyForm();
      } else if ('update' === this.functionType) {

        if (this.scope && (this.scope.row.dataDisposeState === 'add' || this.scope.row.dataDisposeState === 'update')) {
          console.log('update', this.scope)
          setListElement(this.template.list, "id", "itemValue", this.scope.row);
        } else {
          let userQuery = {
            "id": this.scope.row.id,
          };
          mSelectById(this.template.source, userQuery).then((res) => {
            setListElement(this.template.list, "id", "itemValue", res.data.data);
            //给表单的数据赋值
            this.fromData = res.data.data;
            // console.log('fromData', this.fromData);
            // console.log('template', this.template.list);
            for (let i = 0; i < this.template.list; i++) {
              // let itemArray = this.template.list[i]
            }
            for (const listElement of this.template.list) {
              for (const listElementElement of listElement) {
                if (listElementElement.configure.type === 'table') {
                  this.tableListDataInit(listElementElement.configure)
                }
              }
            }
          })
        }

      }
    })
  },
  created() {


  },
  /*创建前，此阶段为实例初始化之后，this指向创建的实例*/
  beforeCreate() {
    // console.log('beforeCreate',  this.config)
    // let par={
    //   jsonKey:this.config._id
    // }
    //获取表单配置
    // this.$getConfig(par).then((res) => {
    //   this.config.fieldLis=res.data;
    //   console.log(res)
    // }).catch(error => {
    //   console.log(error)
    // })
  },

}

</script>

<style scoped lang="less">
.form-main {
  /*内边距*/
  padding: 10px;
  //width: 1500px;
  .container {
    display: flex;
    margin: 20px auto 0;
    justify-content: space-between;

    .col:last-child {
      margin-right: 0; /* 最后一个列不添加右侧间距 */
    }

    .col {
      /* 添加列之间的间距 */
      margin-right: 10px;

      //overflow:auto;
      //overflow: hidden;
      //border: 1px solid red;
      .labelItem {

        display: flex;
        align-items: center; /*垂直居中，针对的是labelItem类下面的子元素，不包含“孙子”元素*/
        /*水平居中，针对的是labelItem类下面的子元素，不包含“孙子”元素*/
        //justify-content: center;
        height: 100%;


        .inputFileItem {
          display: none;
          border: 1px solid red;
        }

        .rowItem {

          display: flex;
          justify-content: center;
          align-items: center;

          .itemImgBox {
            max-width: 100%;
            padding: 5px;
            border: 1px solid aliceblue;
            position: relative;
            display: inline-block;
            /*图片显示区域*/

            .itemImgShowBox :hover {
              //鼠标样式 手
              //cursor: pointer;
            }

            /*图片删除样式*/

            .itemImgDelBox {
              cursor: pointer;
              position: absolute;
              top: 5px; /* 距离顶部的距离 */
              /* 距离右侧的距离 */
              right: 5px;
              display: none;
              //background-color: green;
              color: green;
              z-index: 100;

              //width: 0;
              //height: 0;
              //border-left: 20px solid transparent;
              //border-right: 20px solid transparent;
              //border-bottom: 20px solid green;
              //position: absolute;
              //top: 0;
              //right: -5px;
              //transform: rotate(45deg); /* 添加旋转 */
            }

            .itemImgDelBox :hover {
              //鼠标样式 手
              cursor: pointer;

            }
          }
        }

        /*label文字*/

        .spanItem {
          padding: 0 5px 0 0;
          width: 100px;
          /*设置文字右对齐*/
          text-align: right;
          //border: 1px solid red;
        }

        /*表单中的表格样式*/

        .tableItem {

          //border: 1px solid red;
          width: 950px;
          //flex: 0 1 calc((100% - 20px) / 24 * 24);
        }

        /* 输入框的外层容器样式 */

        .inputItem {
          display: inline-block;
          height: 36px;
          line-height: 36px;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          padding: 0 12px;
          box-sizing: border-box;
          font-size: 14px;
          color: #606266;
          width: 100%;
        }

        /* 输入框内部文字样式 */

        .inputItem input {
          border: none;
          outline: none;
          width: 100%;
          height: 100%;
          background-color: transparent;
          font-size: 14px;
          color: #606266;
        }

        /* 输入框激活状态样式 */

        .inputItem:focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }

        /* 输入框禁用状态样式 */

        .inputItem:disabled {
          background-color: #f5f7fa;
          color: #c0c4cc;
          cursor: not-allowed;
        }

      }


    }
  }

  /*按钮区域*/

  .form-button {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}


</style>
